<template>
<div id="DailiList" class="page-blank">
  <van-nav-bar title="代理" left-arrow @click-left="goBack()" v-if="!userId"/>
  <van-search v-model="searchValue" placeholder="请输入代理名称或代理手机号" show-action shape="round">        
    <div slot="action" @click="onSearch" class="ft-blue">搜索</div>
  </van-search>
  <div class="flex-body">   
    <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="getList">
      <div class="role-people-box" v-for="(v,i) in list" :key="i">
        <div class="people-title">
          <img :src="v.icon || './logo.png'" style="display: inline-block;">
          <div class="left">
            <div>{{ v.nick }}({{ v.userId }})</div>
            <div>提成比:{{ v.virtualProportion }}%</div>
          </div>
          <div class="right" v-if="v.userId != $store.state.userInfo.userId">
            <div class="btn" @click="modify( v )"></div>
          </div>
        </div>
        <div class="people-main">
          <div class="label">
            <span>用户名</span>
            <span class="right">{{ v.userName }}</span>
          </div>
          <div class="label">
            <span>手机号</span>
            <span class="right">{{ v.phone }}</span>
          </div>
          <div class="label" v-if="$store.state.userInfo.roleType == 0">
            <span>订单管理</span>
            <span class="right" @click="order.showBlank(v.userId)">设置</span>
          </div>
          <div class="label" v-if="$store.state.userInfo.roleType == 0">
            <span>代理级别</span>
            <span class="right">{{ v.level }}</span>
          </div>
          <div class="label" v-if="$store.state.userInfo.roleType == 0">
            <span>下级代理数</span>
            <span class="right" @click="lookSecond(v.userId, 1)">{{ v.agentNum || 0 }}</span>
          </div>
          <div class="label">
            <span>商户数</span>
            <span class="right" @click="lookSecond(v.userId, 2)">{{ v.shopManagerNum || 0 }}</span>
          </div>
          <div class="label">
            <span>门店数</span>
            <span class="right">{{ v.shopNum || 0 }}</span>
          </div>
          <div class="label">
            <span>设备数</span>
            <span class="right">{{ v.terminalNum || 0 }}</span>
          </div>
          <div class="label" v-if="$store.state.userInfo.roleType == 0">
            <span>余额</span>
            <span class="right" style="color: red">{{ v.wallet || 0 }}</span>
          </div>
          <div class="label" v-if="$store.state.userInfo.roleType == 0">
            <span>绑定设备</span>
            <span class="right" style="color: #1989fa;" @click="bangding(v.userId)">绑定</span>
          </div>
        </div>
      </div>
    </van-list>
  </div>
  
  <van-popup v-model="order.show" position="bottom" :style="{ height: '100%' }">
    <div class="page-blank">
      <van-nav-bar title="订单设置" left-arrow @click-left="order.show = false"/>
      <div class="flex-body">
        <van-cell-group>  
          <van-field v-model="order.detail.dayMinOrder" required label="最低单数" placeholder="请输入"/>
          <van-field v-model="order.detail.loseOrder" required label="抽单间隔" placeholder="请输入"/>
          <van-field readonly clickable label="开始时间" :value="order.detail.startTime" required placeholder="请选择" @click="riqi.showBlank()"/>
          <van-field readonly clickable label="开关" :value="status.name[order.detail.status]" required placeholder="请选择" @click="status.show = true"/>
          <van-button round type="info" size="small" :loading="order.submitLoading" @click="order.submit">提交</van-button>
        </van-cell-group> 
      </div>
    </div>
  </van-popup>

  <van-popup v-model="riqi.show" position="bottom" v-if="riqi.show">
    <van-datetime-picker v-model="riqi.value" type="date-time" :formatter="formatter" @cancel="riqi.show = false" @confirm="riqi.changeDate"/>
  </van-popup>

  <van-popup v-model="status.show" position="bottom">
    <van-picker show-toolbar :columns="status.columns" @cancel="status.show = false" @confirm="status.confirm"/>
  </van-popup>

  <van-popup v-model="second.blank" position="bottom" :style="{ height: '100%' }">
    <div class="page-blank">
      <van-nav-bar :title="`下级${ second.type == 1 ? '代理' : '商户' }`" left-arrow @click-left="second.blank = false"/>
      <DaiLi :userId="second.userId" v-if="second.type == 1" class="flex-body"></DaiLi>
      <shop-list :userId="second.userId" v-else class="flex-body"></shop-list>
    </div>
  </van-popup>
</div>
</template>

<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator';
import axios from '@/utils/request';
import { formatDate } from '@/utils/common';
import ShopList from './ShopList.vue';
import DaiLi from './DaiLi.vue';
declare const wx: any;

@Component({ components: { ShopList, DaiLi } })
export default class DailiList extends Vue {
  @Prop() userId: any;
  roleType: any = this.$store.state.userInfo.roleType
  list: any = []
  page: any = 1
  loading: any = false
  finished: any = false
  searchValue: any = ''
  dlUserId: any = ''

  onSearch() {
    this.page = 1
    this.list = [];
    this.loading = true;
    this.finished = false;
    this.getList()
  }
  getList() {
    let page = this.page;
    let query: any = { page, size: 10, userId: this.userId || this.$store.state.userInfo.userId };
    if ( this.searchValue ) query.content = this.searchValue;
    axios.get('/api/roleController/agentList', query).then((res: any) => {    
      if ( this.page != page ) { return ; }
      this.page = this.page + 1;      
      let list = res.list || [];
      this.loading = false;
      this.list.push( ...list );
      if(res.isLastPage) this.finished = true;
    }).catch(() => {
      this.loading = false;
      this.finished = true;
    });
  }
  modify(shop: any) {

    axios.get('/api/roleController/getUserRoleInfo', { 
      userId: shop.userId 
    }).then((res: any) => {
      console.log(res);
      this.$router.push({ name: 'AddJuese', query: { type: 'modify' }, params: res });
    });
  }

  bangding(userId: any) {
    this.dlUserId = userId;
    let config = this.$store.state.config;
    wx.config({ ...config, debug: false, jsApiList: [ 'scanQRCode', 'chooseImage', 'uploadImage', 'getLocation', 'openLocation' ] });
    wx.scanQRCode({
      needResult: 1, 
      scanType: [ "qrCode" ], 
      success: (res: any) => {
        let result = res.resultStr; 
        if ( result.indexOf('dianxiaotong') > -1 ) {
          let sn = result.split('=')[1];
          if ( isNaN( sn[0] ) ) {
            axios.get('/api/chargerPlaEquipmentController/getSnById', {
              id: result.split('=')[1]
            }).then((res: any) => {
              this.inState( res );
            });
          } else {
            this.inState( sn );
          }
        } else {
          if ( result.indexOf('=')>0 ) {
            this.inState( result.split('=')[1] );
          } else {
            this.inState( result );
          }
        }
      }
    });
  }
  inState( sn: any ) {
    axios.post('/api/bubao/bangdingdl', { 
      sn, userId: this.dlUserId
    }).then((res: any) => {
      this.$toast('设备绑定成功');
    });
  }

  order: any = {
    show: false,
    detail: {},
    type: 'add',
    submitLoading: false,
    showBlank: (userId: any) => {
      axios.get(`/api/hideOrder/${userId}`).then((res: any) => {
        this.order.userId = userId;
        if(res) {
          this.order.detail = { dayMinOrder: res.dayMinOrder, loseOrder: res.loseOrder, startTime: res.startTime, status: res.status };
          this.order.type = 'updata';
        } else {
          this.order.detail = { dayMinOrder: 10, loseOrder: 10, startTime: formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss'), status: 0 };
          this.order.type = 'add';
        }
        this.order.show = true;
      });
    },
    submit: () => {
      let detail = JSON.parse(JSON.stringify(this.order.detail));
      detail.userId = this.order.userId;
      if (isNaN(detail.dayMinOrder)) { this.$toast('最低单数需要输入数字！'); return; }
      if (isNaN(detail.loseOrder)) { this.$toast('抽单间隔需要输入数字！'); return; }
      this.order.submitLoading = true;
      if (this.order.type == 'add') {
        axios.post('/api/hideOrder', detail).then((res: any) => {
          this.$toast('新增成功！');
          this.order.submitLoading = false;
          this.order.show = false;
        }).catch(() => {
          this.order.submitLoading = false;
        });
      } else {
        axios.put('/api/hideOrder', detail).then((res: any) => {
          this.$toast('修改成功！');
          this.order.submitLoading = false;
          this.order.show = false;
        }).catch(() => {
          this.order.submitLoading = false;
        });
      }
    }
  }
  riqi: any = {
    value: new Date(),
    show: false,
    showBlank: () => {
      if (this.order.detail.startTime) {
        this.riqi.value = new Date(this.order.detail.startTime);
      } else {
        this.riqi.value = new Date();
      }
      this.riqi.show = true;
    },
    changeDate: (date: any) => {
      console.log(date, 'date');
      let dateObj = new Date(date);
      let detail = JSON.parse(JSON.stringify(this.order.detail));
      detail.startTime = formatDate(dateObj, 'yyyy-MM-dd HH:mm:ss');
      this.order.detail = detail;
      this.riqi.show = false;
    }
  }
  status: any = {
    show: false,
    columns: [
      { value: 0, text: '开' },
      { value: 1, text: '关' },
    ],
    name: [ '开', '关' ],  
    confirm: (option: any) => {
      let detail = JSON.parse(JSON.stringify(this.order.detail));
      detail.status = option.value;
      this.order.detail = detail;
      this.status.show = false;
    }
  }
  formatter(type: string, value: any) {
    let nameJson: any = { year: '年', month: '月', day: '日', hour: '', minute: '' };
    return value + nameJson[ type ];
  }

  second: any = {
    blank: false,
    userId: '',
    type: 1,
  }
  lookSecond(userId: any, type: any) {
    this.second.userId = userId;
    this.second.type = type;
    this.second.blank = true;
  }

  goBack() {
    this.$router.go(-1);
  }

  mounted() {
  }
  
};
</script>

<style lang="scss">
#DailiList { 
  .role-people-box {
    line-height: 26px;
    background: #fff;
    box-shadow: 3px 7px 20px 0px rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    padding: 0 10px;
    box-sizing: border-box;
    font-size: 0.28rem;
    width: 6.7rem; 
    margin: 0.1rem auto;
    .people-title {
      line-height: 57px;
      font-size: 15px;
      .left {
        display: inline-block;
        line-height: 20px;
        vertical-align: middle;
        padding-left: 10px;
      }
      img {
        height: 35px;
        width: 35px;
        vertical-align: middle;
      }
      .right {
        float: right;
        color: #0086d1;
        .btn {
          margin-left: 10px;
          display: inline-block;
          height: 18px;
          width: 18px;
          background: url(~@/assets/img/main/modify.png) no-repeat center;
          background-size: 18px 18px;
        }
      }
    }
    .people-main {
      font-size: 15px;
      .label {
        height: 50px;
        line-height: 50px;
        color: #666666;
        border-bottom: 1px solid #ebebeb;
        &:last-child {
          border-bottom: none;
        }
      }
      .right {
        float: right;
        color: #333333;
      }
    }
    .data-main {
      padding: 5px 0;
      .label {
        color: #0086d1;
      }
    }  
  }
}
</style>

